'''
尊享人生医疗保险（2018版）
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()

        self.name = "尊享人生医疗保险（2018版）"

    # 生成产品信息
    def genProductInfo(self):
        # 年龄段
        years = [str(i) for i in range(0, 61)]
        # 可选方案 A 方案 1109 B 方案 1120
        plan = ["1109", "1120"]
        #有无社保 0 无社保 1 有社保
        socialSec = ["0","1"]


        for v in product(years, plan,socialSec):

            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1],v[2]))

            self.mysql._conn.commit()

            print("%s产品写入数据库成功" % self.name)

    # 执行爬虫
    def requestJson(self,dt=None):

        data = {"saleItemId": 10047, "plan": dt["plan"], "birthDate": "{year}-11-15".format( year = str( 2019- int( dt["year"]))), "hasSocialSecurity":dt["socialSec"],
                "premPeriodNumber": "single", "policyPeriodNumber": "term_1", "sumAssured": "2000000"}

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=json.dumps( data ))

        print( r.text )
        if r.status_code == 200:

            price = Helper.decimalParse( r.json()["data"]["totalPermium"])

            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price,
            }



            # 执行数据库更新操作
            self.mysql.updatePrice(data)

            print("产品价格更新成功:", data["price"])

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask( data )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )



if __name__ == '__main__':
    s = Spider()
    s.genProductInfo()
    s.main()
